package com.xafc.demo.security.core;

import cn.hutool.core.util.StrUtil;
import com.xafc.demo.security.config.JwtSecurityProperties;
import com.xafc.demo.security.utils.CookieUtils;
import com.xafc.demo.security.utils.JwtTokenUtil;
import com.xafc.demo.security.utils.UserHolderUtils;
import com.xafc.demo.security.utils.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtSecurityProperties jwtSecurityProperties;

    @Autowired
    @Qualifier("userDetailServiceImpl")
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1、获取Token
        final String token;
        if(StrUtil.isNotEmpty(request.getHeader(jwtSecurityProperties.getHttpHeadName()))){
            token = request.getHeader(jwtSecurityProperties.getHttpHeadName());
        }else{
            final Cookie cookie = CookieUtils.getCookieByName(request, jwtSecurityProperties.getCookieName());
            if(cookie == null){
                chain.doFilter(request, response);
                return;
            }
            token = cookie.getValue();
        }

        // 2、验证Token
        if(JwtTokenUtil.isTokenExpired(token)){
            CookieUtils.deleteCookie(request, response, jwtSecurityProperties.getCookieName());
            chain.doFilter(request, response);
            return;
        }

        // 3、通过Token获取当前用户
        final CurrentUser currentUser = JwtTokenUtil.parseJWTToUserInfo(token);
        // 4、将当前用户设置到UserHolder中，不设置也可以通过SecurityContextHolder.getContext().getAuthentication().getPrincipal()获取当前用户的所有信息
        if(UserHolderUtils.getUser() != null){
            UserHolderUtils.remove();
        }
        UserHolderUtils.setUser(currentUser);

        // 5、获取当前用户设置到SecurityContext中
        final UserDetails userDetails = this.userDetailsService.loadUserByUsername(currentUser.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // SecurityContext中存在authentication对象就证明登录成功了
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 6、放行
        chain.doFilter(request, response);
    }

}


